import { useEffect, useRef } from 'react';
import { useAppStore } from '@/stores/appStore';

export function usePerformanceMonitor() {
  const { updatePerformance } = useAppStore();
  const frameCountRef = useRef(0);
  const lastTimeRef = useRef(performance.now());
  const animationFrameRef = useRef<number>();
  
  useEffect(() => {
    const measurePerformance = () => {
      const now = performance.now();
      frameCountRef.current++;
      
      // Calculate FPS every second
      if (now - lastTimeRef.current >= 1000) {
        const fps = Math.round(frameCountRef.current * 1000 / (now - lastTimeRef.current));
        
        // Get memory usage if available
        const memoryUsage = (performance as any).memory ? 
          Math.round((performance as any).memory.usedJSHeapSize / 1024 / 1024) : 0;
        
        updatePerformance({
          frameRate: fps,
          memoryUsage,
        });
        
        frameCountRef.current = 0;
        lastTimeRef.current = now;
      }
      
      animationFrameRef.current = requestAnimationFrame(measurePerformance);
    };
    
    // Start monitoring
    animationFrameRef.current = requestAnimationFrame(measurePerformance);
    
    // Monitor network performance
    const observer = new PerformanceObserver((list) => {
      for (const entry of list.getEntries()) {
        if (entry.entryType === 'measure') {
          updatePerformance({
            apiLatency: entry.duration
          });
        }
      }
    });
    
    observer.observe({ entryTypes: ['measure'] });
    
    return () => {
      if (animationFrameRef.current) {
        cancelAnimationFrame(animationFrameRef.current);
      }
      observer.disconnect();
    };
  }, [updatePerformance]);
  
  // Monitor page load performance
  useEffect(() => {
    const navigation = performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming;
    if (navigation) {
      updatePerformance({
        loadTime: navigation.loadEventEnd - navigation.loadEventStart
      });
    }
  }, [updatePerformance]);
}